<?php
namespace App\Controllers\Common;

use App\Libs\Mail\Mail;
use App\Models\User\User;
use App\Libs\Views\Json;
use App\Libs\Base\Constant;
use App\Libs\Captcha\Algorithms\Numeric;
use App\Libs\Session\Session;
use App\Libs\Cache\Redis;
class SetMail extends \App\Libs\Base\BaseAction
{

    static $prefix = 'email';
	public function execute(){
        $user = $this->session->user??[];
        if(empty($user)){
            return Json::view(Constant::UNLOGIN,'请登录',NULL);
        }
        if(!$this->request->hasQuery('address')){
            return Json::view(1,'缺少邮箱',NULL);
        }
        $emailAddress = $this->request->getQuery('address');
        if($this->request->hasQuery('captcha')){
            $capcha = $this->request->getQuery('captcha');
            $key = $emailAddress;
            $storeCaptcha = Redis::get(self::$prefix.$key);
            if(empty($storeCaptcha)){
                return Json::view(1,'验证失败，请重试',NULL);
            }
            if($capcha==$storeCaptcha){

                $matchUser = User::findOne([
                    'email=?1',
                    'bind'=>[1=>$emailAddress]
                ]);
                if(!empty($matchUser)){
                    return Json::view(1,'你绑定的邮箱已经绑定到其他账户',NULL);
                }
                $userData = User::findOne([
                    'id=?1',
                    'bind'=>[1=>$user->id]
                ]);
                $userData->email = $emailAddress;
                if($userData->save()){
                    Session::resetCache($userData);
                    Redis::delete(self::$prefix.$key);
                    return Json::view(0,'邮箱保存成功',NULL);
                }else{
                    return Json::view(1,'保存失败，请重试',NULL);
                }
            }else{
                return Json::view(1,'验证码不正确',NULL);
            }

        }else{
            $capcha = Numeric::instance()->generate(6);
            $txt = '您的验证码是：'.$capcha['captcha'];
            $res = Mail::mail163($emailAddress,'邮箱验证',$txt);
            if(is_array($res)){
                return Json::view(1,'发送失败',$res);
            }else{
                $key = $emailAddress;
                Redis::setex(self::$prefix.$key, 10*60, $capcha['captcha'] );
                return Json::view(0,'ok',['capcha'=>$capcha['captcha']]);
            }
        }







////        return \App\Libs\Views\Json::view(0, '成功', $number['captcha']);
    }


}
